﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using digit.Core;

namespace SMS.CDR
{
    public partial class CDRMonitor : System.Windows.Forms.Form
    {
        // Fields
        private string CDRDirVMS;
        private IContainer components;
        private int mkFolder;
        private string DateCDR;
        private string PassFTPVMS;
        private int SeqNumVms;
        private string nameCdr;
        private string ServerFTPVMS;
        private Timer timeWrite;
        private string UserFTPVMS;
        private GroupBox gbxVMS;
        private TextBox txtTimeVMS;
        private Label label19;
        private TextBox txtDirVMS;
        private Label label20;
        private TextBox txtPassVMS;
        private Label label21;
        private TextBox txtUserVMS;
        private Label label22;
        private TextBox txtServerVMS;
        private Label label23;
        private TextBox txtWriterLog;
        private TabPage tabWriter;
        private TabControl tabCDR;
        private Button btnStartVms;
        private TabPage tabFTP;
        private Button btnExit;
        private Button btnClear;
        private Button btnResendVms;
        private CheckBox chkEnableTransfer;
        private TextBox txtLogFtp;

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.timeWrite = new System.Windows.Forms.Timer(this.components);
            this.tabWriter = new System.Windows.Forms.TabPage();
            this.btnExit = new System.Windows.Forms.Button();
            this.btnClear = new System.Windows.Forms.Button();
            this.btnStartVms = new System.Windows.Forms.Button();
            this.gbxVMS = new System.Windows.Forms.GroupBox();
            this.txtTimeVMS = new System.Windows.Forms.TextBox();
            this.label19 = new System.Windows.Forms.Label();
            this.txtDirVMS = new System.Windows.Forms.TextBox();
            this.label20 = new System.Windows.Forms.Label();
            this.txtPassVMS = new System.Windows.Forms.TextBox();
            this.label21 = new System.Windows.Forms.Label();
            this.txtUserVMS = new System.Windows.Forms.TextBox();
            this.label22 = new System.Windows.Forms.Label();
            this.txtServerVMS = new System.Windows.Forms.TextBox();
            this.label23 = new System.Windows.Forms.Label();
            this.txtWriterLog = new System.Windows.Forms.TextBox();
            this.tabCDR = new System.Windows.Forms.TabControl();
            this.tabFTP = new System.Windows.Forms.TabPage();
            this.btnResendVms = new System.Windows.Forms.Button();
            this.chkEnableTransfer = new System.Windows.Forms.CheckBox();
            this.txtLogFtp = new System.Windows.Forms.TextBox();
            this.tabWriter.SuspendLayout();
            this.gbxVMS.SuspendLayout();
            this.tabCDR.SuspendLayout();
            this.tabFTP.SuspendLayout();
            this.SuspendLayout();
            // 
            // timeWrite
            // 
            this.timeWrite.Tick += new System.EventHandler(this.timeCDRVMS_Tick);
            // 
            // tabWriter
            // 
            this.tabWriter.Controls.Add(this.btnExit);
            this.tabWriter.Controls.Add(this.btnClear);
            this.tabWriter.Controls.Add(this.btnStartVms);
            this.tabWriter.Controls.Add(this.gbxVMS);
            this.tabWriter.Controls.Add(this.txtWriterLog);
            this.tabWriter.Location = new System.Drawing.Point(4, 22);
            this.tabWriter.Name = "tabWriter";
            this.tabWriter.Size = new System.Drawing.Size(616, 282);
            this.tabWriter.TabIndex = 1;
            this.tabWriter.Text = "CDR Writer";
            this.tabWriter.UseVisualStyleBackColor = true;
            // 
            // btnExit
            // 
            this.btnExit.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnExit.Location = new System.Drawing.Point(499, 84);
            this.btnExit.Name = "btnExit";
            this.btnExit.Size = new System.Drawing.Size(102, 26);
            this.btnExit.TabIndex = 23;
            this.btnExit.Text = "&Exit";
            this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
            // 
            // btnClear
            // 
            this.btnClear.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnClear.Location = new System.Drawing.Point(499, 54);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(102, 26);
            this.btnClear.TabIndex = 22;
            this.btnClear.Text = "&Clear";
            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
            // 
            // btnStartVms
            // 
            this.btnStartVms.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnStartVms.Location = new System.Drawing.Point(499, 17);
            this.btnStartVms.Name = "btnStartVms";
            this.btnStartVms.Size = new System.Drawing.Size(102, 31);
            this.btnStartVms.TabIndex = 21;
            this.btnStartVms.Text = "&Start";
            this.btnStartVms.Click += new System.EventHandler(this.btnStartVms_Click);
            // 
            // gbxVMS
            // 
            this.gbxVMS.Controls.Add(this.txtTimeVMS);
            this.gbxVMS.Controls.Add(this.label19);
            this.gbxVMS.Controls.Add(this.txtDirVMS);
            this.gbxVMS.Controls.Add(this.label20);
            this.gbxVMS.Controls.Add(this.txtPassVMS);
            this.gbxVMS.Controls.Add(this.label21);
            this.gbxVMS.Controls.Add(this.txtUserVMS);
            this.gbxVMS.Controls.Add(this.label22);
            this.gbxVMS.Controls.Add(this.txtServerVMS);
            this.gbxVMS.Controls.Add(this.label23);
            this.gbxVMS.Location = new System.Drawing.Point(11, 12);
            this.gbxVMS.Name = "gbxVMS";
            this.gbxVMS.Size = new System.Drawing.Size(473, 100);
            this.gbxVMS.TabIndex = 19;
            this.gbxVMS.TabStop = false;
            this.gbxVMS.Text = "FTP Info";
            // 
            // txtTimeVMS
            // 
            this.txtTimeVMS.Location = new System.Drawing.Point(300, 17);
            this.txtTimeVMS.Name = "txtTimeVMS";
            this.txtTimeVMS.Size = new System.Drawing.Size(60, 20);
            this.txtTimeVMS.TabIndex = 18;
            this.txtTimeVMS.Text = "30";
            // 
            // label19
            // 
            this.label19.Location = new System.Drawing.Point(220, 21);
            this.label19.Name = "label19";
            this.label19.Size = new System.Drawing.Size(73, 16);
            this.label19.TabIndex = 19;
            this.label19.Text = "Timer Interval";
            // 
            // txtDirVMS
            // 
            this.txtDirVMS.Location = new System.Drawing.Point(300, 48);
            this.txtDirVMS.Name = "txtDirVMS";
            this.txtDirVMS.Size = new System.Drawing.Size(157, 20);
            this.txtDirVMS.TabIndex = 16;
            this.txtDirVMS.Text = "D:\\vn1102\\CDR\\CDRVMS\\";
            // 
            // label20
            // 
            this.label20.Location = new System.Drawing.Point(220, 51);
            this.label20.Name = "label20";
            this.label20.Size = new System.Drawing.Size(71, 16);
            this.label20.TabIndex = 17;
            this.label20.Text = "Client Store";
            // 
            // txtPassVMS
            // 
            this.txtPassVMS.Location = new System.Drawing.Point(98, 72);
            this.txtPassVMS.Name = "txtPassVMS";
            this.txtPassVMS.PasswordChar = '*';
            this.txtPassVMS.Size = new System.Drawing.Size(101, 20);
            this.txtPassVMS.TabIndex = 14;
            this.txtPassVMS.Text = "1alorylmoto2";
            // 
            // label21
            // 
            this.label21.Location = new System.Drawing.Point(26, 72);
            this.label21.Name = "label21";
            this.label21.Size = new System.Drawing.Size(56, 16);
            this.label21.TabIndex = 15;
            this.label21.Text = "Password";
            // 
            // txtUserVMS
            // 
            this.txtUserVMS.Location = new System.Drawing.Point(98, 44);
            this.txtUserVMS.Name = "txtUserVMS";
            this.txtUserVMS.Size = new System.Drawing.Size(101, 20);
            this.txtUserVMS.TabIndex = 12;
            this.txtUserVMS.Text = "dec";
            // 
            // label22
            // 
            this.label22.Location = new System.Drawing.Point(25, 46);
            this.label22.Name = "label22";
            this.label22.Size = new System.Drawing.Size(64, 16);
            this.label22.TabIndex = 13;
            this.label22.Text = "User Name";
            // 
            // txtServerVMS
            // 
            this.txtServerVMS.Location = new System.Drawing.Point(98, 16);
            this.txtServerVMS.Name = "txtServerVMS";
            this.txtServerVMS.Size = new System.Drawing.Size(101, 20);
            this.txtServerVMS.TabIndex = 10;
            this.txtServerVMS.Text = "10.50.9.248";
            // 
            // label23
            // 
            this.label23.Location = new System.Drawing.Point(26, 20);
            this.label23.Name = "label23";
            this.label23.Size = new System.Drawing.Size(56, 16);
            this.label23.TabIndex = 11;
            this.label23.Text = "Server";
            // 
            // txtWriterLog
            // 
            this.txtWriterLog.Location = new System.Drawing.Point(11, 126);
            this.txtWriterLog.Multiline = true;
            this.txtWriterLog.Name = "txtWriterLog";
            this.txtWriterLog.ReadOnly = true;
            this.txtWriterLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtWriterLog.Size = new System.Drawing.Size(590, 145);
            this.txtWriterLog.TabIndex = 14;
            // 
            // tabCDR
            // 
            this.tabCDR.Controls.Add(this.tabWriter);
            this.tabCDR.Controls.Add(this.tabFTP);
            this.tabCDR.Location = new System.Drawing.Point(9, 3);
            this.tabCDR.Name = "tabCDR";
            this.tabCDR.SelectedIndex = 0;
            this.tabCDR.Size = new System.Drawing.Size(624, 308);
            this.tabCDR.TabIndex = 0;
            // 
            // tabFTP
            // 
            this.tabFTP.Controls.Add(this.btnResendVms);
            this.tabFTP.Controls.Add(this.chkEnableTransfer);
            this.tabFTP.Controls.Add(this.txtLogFtp);
            this.tabFTP.Location = new System.Drawing.Point(4, 22);
            this.tabFTP.Name = "tabFTP";
            this.tabFTP.Padding = new System.Windows.Forms.Padding(3);
            this.tabFTP.Size = new System.Drawing.Size(616, 282);
            this.tabFTP.TabIndex = 2;
            this.tabFTP.Text = "FTP Transfer";
            this.tabFTP.UseVisualStyleBackColor = true;
            // 
            // btnResendVms
            // 
            this.btnResendVms.Location = new System.Drawing.Point(501, 10);
            this.btnResendVms.Name = "btnResendVms";
            this.btnResendVms.Size = new System.Drawing.Size(102, 31);
            this.btnResendVms.TabIndex = 25;
            this.btnResendVms.Text = "&Re-send";
            this.btnResendVms.UseVisualStyleBackColor = true;
            this.btnResendVms.Click += new System.EventHandler(this.btnResendVms_Click);
            // 
            // chkEnableTransfer
            // 
            this.chkEnableTransfer.AutoSize = true;
            this.chkEnableTransfer.Checked = true;
            this.chkEnableTransfer.CheckState = System.Windows.Forms.CheckState.Checked;
            this.chkEnableTransfer.Location = new System.Drawing.Point(13, 22);
            this.chkEnableTransfer.Name = "chkEnableTransfer";
            this.chkEnableTransfer.Size = new System.Drawing.Size(59, 17);
            this.chkEnableTransfer.TabIndex = 23;
            this.chkEnableTransfer.Text = "&Enable";
            this.chkEnableTransfer.UseVisualStyleBackColor = true;
            // 
            // txtLogFtp
            // 
            this.txtLogFtp.Location = new System.Drawing.Point(13, 49);
            this.txtLogFtp.Multiline = true;
            this.txtLogFtp.Name = "txtLogFtp";
            this.txtLogFtp.ReadOnly = true;
            this.txtLogFtp.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtLogFtp.Size = new System.Drawing.Size(590, 222);
            this.txtLogFtp.TabIndex = 15;
            // 
            // CDRMonitor
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(644, 320);
            this.Controls.Add(this.tabCDR);
            this.MaximizeBox = false;
            this.Name = "CDRMonitor";
            this.Text = "VMS CDR Writer & Transfer";
            this.Load += new System.EventHandler(this.CDRMonitor_Load);
            this.tabWriter.ResumeLayout(false);
            this.tabWriter.PerformLayout();
            this.gbxVMS.ResumeLayout(false);
            this.gbxVMS.PerformLayout();
            this.tabCDR.ResumeLayout(false);
            this.tabFTP.ResumeLayout(false);
            this.tabFTP.PerformLayout();
            this.ResumeLayout(false);

        }
        #endregion

        // Methods
        public CDRMonitor()
        {
            this.InitializeComponent();
        }

        private void CDRMonitor_Load(object sender, EventArgs e)
        {
            this.Text = this.Text + " - " + Util.GetAppSettings("ServiceRange");
            this.DateCDR = Util.GetAppSettings("DateCDR");
            this.SeqNumVms = Util.ToInteger(Util.GetAppSettings("SeqNumVms"));

            if (DateTime.Now.ToString("dd/MM/yyyy") != this.DateCDR)
            {
                ConfigSettings.WriteSetting("DateCDR", DateTime.Now.ToString("dd/MM/yyyy"));
                this.DateCDR = DateTime.Now.ToString("dd/MM/yyyy");
            }

            this.mkFolder = Util.ToInteger(Util.GetAppSettings("VmsMkF"));
            if (DateTime.Now.Day != this.mkFolder)
            {
                ConfigSettings.WriteSetting("VmsMkF", DateTime.Now.Day.ToString());
                this.mkFolder = DateTime.Now.Day;
            }
             
        }

        #region Button Events

        private void btnStartVms_Click(object sender, EventArgs e)
        {
            if (this.btnStartVms.Text.ToLower() == "start")
            {
                this.timeWrite.Interval = (Convert.ToInt32(this.txtTimeVMS.Text) * 60) * 0x3e8;
                this.txtTimeVMS.Enabled = false;
                this.CDRDirVMS = this.txtDirVMS.Text;
                this.txtDirVMS.Enabled = false;
                this.ServerFTPVMS = this.txtServerVMS.Text;
                this.txtServerVMS.Enabled = false;
                this.UserFTPVMS = this.txtUserVMS.Text;
                this.txtUserVMS.Enabled = false;
                this.PassFTPVMS = this.txtPassVMS.Text;
                this.txtPassVMS.Enabled = false;
                this.btnStartVms.Text = "Stop";

                if (this.CDRDirVMS.Substring(this.CDRDirVMS.Length - 1) != @"\")
                    this.CDRDirVMS = this.CDRDirVMS + @"\";

                if (!Directory.Exists(this.CDRDirVMS))
                    Directory.CreateDirectory(this.CDRDirVMS);

                if (!Directory.Exists(this.CDRDirVMS + @"Sent\"))
                    Directory.CreateDirectory(this.CDRDirVMS + @"Sent\");

                if (!Directory.Exists(this.CDRDirVMS + @"NotSent\"))
                    Directory.CreateDirectory(this.CDRDirVMS + @"NotSent\");

                this.WriteCDRVMS();
            }
            else
            {
                this.txtTimeVMS.Enabled = true;
                this.txtDirVMS.Enabled = true;
                this.txtServerVMS.Enabled = true;
                this.txtUserVMS.Enabled = true;
                this.txtPassVMS.Enabled = true;
                this.btnStartVms.Text = "Start";
                this.timeWrite.Stop();
            }
        }

        private void btnResendVms_Click(object sender, EventArgs e)
        {
            string str = DateTime.Now.ToString("yyyyMMdd");
            DirectoryInfo info2 = new DirectoryInfo(this.txtDirVMS.Text.Trim());
            foreach (FileInfo info3 in info2.GetFiles("*.cdr"))
            {
                try
                {
                    if (Path.GetFileName(info3.FullName).Length > 19)
                        str = Path.GetFileName(info3.FullName).Substring(10, 8); // Get folder name in file name

                    if (this.mkFolder != DateTime.Now.Day)
                    {
                        ConfigSettings.WriteSetting("VmsMkF", DateTime.Now.Day.ToString());
                        this.mkFolder = DateTime.Now.Day;

                        // Make remote folder over FTP
                        this.MakeDir(DateTime.Now.ToString("yyyyMMdd"));
                    }

                    //Upload file
                    bool result = Upload(str, info3.FullName);

                    if (result)
                    {
                        if (!Directory.Exists(this.CDRDirVMS + @"Sent\" + str + @"\"))
                            Directory.CreateDirectory(this.CDRDirVMS + @"Sent\" + str + @"\");

                        info3.MoveTo(this.CDRDirVMS + @"Sent\" + str + @"\" + info3.Name);
                        this.WriteLog("Transfer CDR file " + this.CDRDirVMS + info3.Name + " successfully " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                    }
                }
                catch (Exception ex4)
                {
                    this.WriteLog("Transfer CDR error: " + ex4.Message);
                    this.timeWrite.Start();
                    return;
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.txtWriterLog.Text = "";
            this.txtLogFtp.Text = "";
        }
        #endregion Button Events

        #region Function

        private void WriteCDRVMS()
        {
            this.timeWrite.Stop();

            SqlConnection cnn = new SqlConnection(Util.GetAppSettings("ConnStrVMS"));
            SqlCommand cmd = new SqlCommand("vn1102_GetCDR", cnn);  // store test: GW_GETCDR_VMS  ||  
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;
            DataSet dataSet = new DataSet();

            SqlCommand cmdError = new SqlCommand("GW_GET_MT_ERROR_VMS", cnn);
            cmdError.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adapterError = new SqlDataAdapter();
            adapterError.SelectCommand = cmdError;
            DataSet dataSetError = new DataSet();            
            try
            {
                cnn.Open();
                adapter.Fill(dataSet);
                adapterError.Fill(dataSetError);
            }
            catch (Exception ex)
            {
                this.WriteLog("Cannot get data: " + ex.Message + "\r\n");
                this.timeWrite.Start();
                return;
            }
            finally
            {
                cnn.Close();
            }
            
            #region Xu ly CDr
             
            if (dataSet.Tables[0].Rows.Count > 0)
            {
                if (this.SeqNumVms < 0x270f)
                {
                    this.SeqNumVms++;
                }
                else
                {
                    this.SeqNumVms = 0;
                }
                ConfigSettings.WriteSetting("SeqNumVms", this.SeqNumVms.ToString());

                this.WriteLog("Start writing CDR " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                string str = DateTime.Now.ToString("yyyyMMdd");
                string fileName = "";

                if (!Directory.Exists(this.CDRDirVMS + @"NotSent\" + str))
                    Directory.CreateDirectory(this.CDRDirVMS + @"NotSent\" + str);

                //fileName = this.CDRDirVMS + @"NotSent\" + str + @"\quangminh_" + DateTime.Now.ToString("yyyyMMdd") + "_" + this.SeqNumVms.ToString("0000") + ".cdr";
                fileName = this.CDRDirVMS + @"NotSent\" + str + @"\" + ConfigSettings.ReadSetting("nameCdr") + @"_" + DateTime.Now.ToString("yyyyMMdd") + "_" + this.SeqNumVms.ToString("0000") + ".cdr";
                
                try
                {
                    // Rename if existence
                    if (File.Exists(fileName))
                        File.Move(fileName, this.CDRDirVMS + @"NotSent\" + str + @"\" + Path.GetFileNameWithoutExtension(fileName) + "_bk.cdr"); 

                    // Create CDR file
                    using (StreamWriter sw = new StreamWriter(File.Open(fileName, FileMode.CreateNew), System.Text.Encoding.UTF8))
                    {
                        string strWrite, strServiceID, strMobileNo, strMsgIn, strMsgOut, strRequestTime, strResponseTime;

                        for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
                        {
                            strWrite = ""; strServiceID = ""; strMobileNo = ""; strMsgIn = ""; strMsgOut = ""; strRequestTime = ""; strResponseTime = "";

                            strServiceID = dataSet.Tables[0].Rows[i]["ServiceID"].ToString();
                            strMsgIn = dataSet.Tables[0].Rows[i]["MsgInContent"].ToString().Trim().Replace(" ", "_");
                            strMsgOut = dataSet.Tables[0].Rows[i]["MsgOutContent"].ToString();
                            strMobileNo = dataSet.Tables[0].Rows[i]["MobileNo"].ToString();
                            strRequestTime = Convert.ToDateTime(dataSet.Tables[0].Rows[i]["RequestTime"]).ToString("yyyyMMddHHmmss");
                            strResponseTime = Convert.ToDateTime(dataSet.Tables[0].Rows[i]["ResponseTime"]).ToString("yyyyMMddHHmmss");

                            // Set main code
                            if (!String.IsNullOrEmpty(strMsgIn) && strMsgIn.IndexOf("_") > 0)
                                strMsgIn = strMsgIn.Substring(0, strMsgIn.IndexOf("_"));

                            if (strMsgIn.Length < 3)
                                strMsgIn = "dec";

                            // Msgout content
                            //strMsgOut = RemoveSpecialChar(strMsgOut); // Remove special character
                            if (!String.IsNullOrEmpty(strMsgOut) && strMsgOut.Length > 6)
                                strMsgOut = strMsgOut.Substring(0, 6);

                            //String to write
                            strWrite = strMobileNo + ":" + "04" + strServiceID.Substring(strServiceID.Length - 4) + ":" + strMsgIn.Substring(0, 2).ToUpper() + ":" + strMsgIn.ToUpper() + ":" + strMobileNo + ":" + strRequestTime + ":" + strResponseTime + ":" + "1:" + strMsgOut;

                            sw.WriteLine(strWrite);
                        }
                        #region xu ly cdr Error
                        if (dataSetError.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < dataSetError.Tables[0].Rows.Count; i++)
                            {
                                strWrite = ""; strServiceID = ""; strMobileNo = ""; strMsgIn = ""; strMsgOut = ""; strRequestTime = ""; strResponseTime = "";
                                                    
                                strServiceID = dataSetError.Tables[0].Rows[i]["ServiceID"].ToString();
                                strMsgIn = dataSetError.Tables[0].Rows[i]["MsgContent"].ToString().Trim().Replace(" ", "_"); //MsgInContent
                                strMsgOut = dataSetError.Tables[0].Rows[i]["MsgContent"].ToString(); //MsgOutContent
                                strMobileNo = dataSetError.Tables[0].Rows[i]["MobileNo"].ToString();
                                strRequestTime = Convert.ToDateTime(dataSetError.Tables[0].Rows[i]["RequestTime"]).ToString("yyyyMMddHHmmss");
                                strResponseTime = Convert.ToDateTime(dataSetError.Tables[0].Rows[i]["RequestTime"]).ToString("yyyyMMddHHmmss");//ResponseTime
                                int procResult = 0;

                                // Set main code
                                if (!String.IsNullOrEmpty(strMsgIn) && strMsgIn.IndexOf("_") > 0)
                                    strMsgIn = strMsgIn.Substring(0, strMsgIn.IndexOf("_"));

                                if (strMsgIn.Length < 3)
                                    strMsgIn = "dec";

                                // Msgout content
                                //strMsgOut = RemoveSpecialChar(strMsgOut); // Remove special character
                                if (!String.IsNullOrEmpty(strMsgOut) && strMsgOut.Length > 6)
                                    strMsgOut = strMsgOut.Substring(0, 6);

                                //String to write
                                strWrite = strMobileNo + ":" + "04" + strServiceID.Substring(strServiceID.Length - 4) + ":" + strMsgIn.Substring(0, 2).ToUpper() + ":" + strMsgIn.ToUpper() + ":" + strMobileNo + ":" + strRequestTime + ":" + strResponseTime + ":" + procResult.ToString() + ":" + strMsgOut;

                                sw.WriteLine(strWrite);
                            }
                        }
                        #endregion
                    }

                    this.WriteLog("Finish writing CDR  " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                //    this.WriteLog("Writing " + dataSet.Tables[0].Rows.Count.ToString() + " record(s) CDR from DB to file " + fileName);
                    this.WriteLog("Writing " + dataSet.Tables[0].Rows.Count.ToString() + " record(s) CDR from DB to file ");
                    this.WriteLog(" And Wrriting " + dataSetError.Tables[0].Rows.Count.ToString() + " cu phap Error  record(s) CDR from DB to file " + fileName);

                    // Update CDR Status=1
                    this.UpdateCDRStatus("ConnStrVMS", 1, this.SeqNumVms.ToString("0000"), "Success");
                }
                catch (Exception ex2)
                {
                    // Delete file has just created
                    File.Delete(fileName);
                    this.SeqNumVms--;
                    ConfigSettings.WriteSetting("SeqNumVms", this.SeqNumVms.ToString());

                    // Update CDR Status=0
                    this.UpdateCDRStatus("ConnStrVMS", 0, "", ex2.ToString().Substring(0, 250));

                    this.WriteLog("Writing CDR error: " + ex2.Message);
                    this.timeWrite.Start();
                    return;
                }
            }
             
            #endregion
                                
            
            if (chkEnableTransfer.Checked)
                this.TransferCdr();
            
            this.timeWrite.Start();
        }

        private void TransferCdr()
        {
            string str = DateTime.Now.ToString("yyyyMMdd");

            DirectoryInfo info2 = new DirectoryInfo(this.CDRDirVMS + @"NotSent\" + str + @"\");
            foreach (FileInfo info3 in info2.GetFiles("*.cdr"))
            {
                if (Path.GetFileName(info3.FullName).Length > 19)
                    str = Path.GetFileName(info3.FullName).Substring(10, 8); // Get folder name in file name

                if (this.mkFolder != DateTime.Now.Day)
                {
                    ConfigSettings.WriteSetting("VmsMkF", DateTime.Now.Day.ToString());
                    this.mkFolder = DateTime.Now.Day;

                    // Make remote folder over FTP
                    this.MakeDir(DateTime.Now.ToString("yyyyMMdd"));
                }

                bool result = Upload(str, info3.FullName);

                if (result)
                {
                    if (!Directory.Exists(this.CDRDirVMS + @"Sent\" + str))
                        Directory.CreateDirectory(this.CDRDirVMS + @"Sent\" + str);

                    info3.MoveTo(this.CDRDirVMS + @"Sent\" + str + @"\" + info3.Name);
                    this.WriteLogFTP("Moved file " + info3.Name + " to " + this.CDRDirVMS + @"Sent\" + str + @"\" + " successfully at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                }
            }
        }

        #region Transfer FTP
        /// <summary>
        /// Method to upload the specified file to the specified FTP Server
        /// </summary>
        /// <param name="filename">file full name to be uploaded</param>
        private bool Upload(string dirname, string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            FtpWebRequest reqFTP;

            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + this.txtServerVMS.Text.Trim() + "/" + dirname + "/" + fileInf.Name));

            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(this.txtUserVMS.Text.Trim(), this.txtPassVMS.Text.Trim());

            // By default KeepAlive is true, where the control connection is not closed after a command is executed.
            reqFTP.KeepAlive = false;

            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            reqFTP.UseBinary = true;

            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileStream fs = fileInf.OpenRead();

            try
            {
                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();

                this.WriteLogFTP("Transfer file " + fileInf.Name + " successful at " + DateTime.Now);

                return true;
            }
            catch (Exception ex)
            {
                this.WriteLogFTP(string.Format("Upload failed: {0}", ex.Message));
                return false;
            }
        }

        private void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                // dirName = name of the directory to create.
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + this.txtServerVMS.Text.Trim() + "/" + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(this.txtUserVMS.Text.Trim(), this.txtPassVMS.Text.Trim());
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();

                this.WriteLogFTP(string.Format("Folder named {0} has created.", dirName));
            }
            catch
            {
                this.WriteLogFTP("Make ftp folder failed, may already!");
            }
        }
        #endregion Transfer FTP

        #region Write Log
        private void WriteLogFTP(string s)
        {
            lock (this.txtLogFtp)
            {
                if ((this.txtLogFtp.TextLength + s.Length) > (int)0x8000)
                {
                    this.txtLogFtp.Clear();
                }
                this.txtLogFtp.AppendText(s + Environment.NewLine);
                this.txtLogFtp.ScrollToCaret();
            }
        }

        private void WriteLog(string s)
        {
            lock (this.txtWriterLog)
            {
                if ((this.txtWriterLog.TextLength + s.Length) > (int)0x8000)
                {
                    this.txtWriterLog.Clear();
                }
                this.txtWriterLog.AppendText(s + Environment.NewLine);
                this.txtWriterLog.ScrollToCaret();
            }
        }
        #endregion Write Log

        #region Functions
        private void UpdateCDRStatus(string cnnStr, byte statusCdr, string CdrIndex, string exStr)
        {
            SqlConnection cnn = new SqlConnection(Util.GetAppSettings(cnnStr));
            SqlCommand cmd = new SqlCommand("vn1102_Update_CDR_Status", cnn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@CDRStatus", SqlDbType.TinyInt).Value = statusCdr;
            cmd.Parameters.Add("@CDRIndex", SqlDbType.VarChar).Value = CdrIndex;
            cmd.Parameters.Add("@ExceptionString", SqlDbType.VarChar).Value = exStr;

            try
            {
                cnn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                this.WriteLog("Cannot execute SP: " + ex.Message + "\r\n");
                return;
            }
            finally
            {
                cnn.Close();
            }
        }

        public static string RemoveSpecialChar(string unicodeString)
        {
            try
            {
                // Remove VietNamese character
                unicodeString = unicodeString.ToLower();
                unicodeString = Regex.Replace(unicodeString, "[áàảãạâấầẩẫậăắằẳẵặ]", "a");
                unicodeString = Regex.Replace(unicodeString, "[éèẻẽẹêếềểễệ]", "e");
                unicodeString = Regex.Replace(unicodeString, "[iíìỉĩị]", "i");
                unicodeString = Regex.Replace(unicodeString, "[óòỏõọơớờởỡợôốồổỗộ]", "o");
                unicodeString = Regex.Replace(unicodeString, "[úùủũụưứừửữự]", "u");
                unicodeString = Regex.Replace(unicodeString, "[yýỳỷỹỵ]", "y");
                unicodeString = Regex.Replace(unicodeString, "[đ]", "d");

                // Remove space
                unicodeString = unicodeString.Replace(" ", "");

                // Remove special character
                //unicodeString = Regex.Replace(unicodeString, "[`-=+:;'?/><,.]", "");
                unicodeString = Regex.Replace(unicodeString, "[`!-+=?>.<,{}[]|]\\]", "");

                return unicodeString;
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion Functions

        #endregion

        #region Timer Events

        private void timeCDRVMS_Tick(object sender, EventArgs e)
        {
            this.WriteCDRVMS();
        }

        #endregion Timer Events     
    }
}